from ysm import settings

import os

import hashlib


def saveupfile(fileobj, upload='upload'):
    """
    将上传的文件保存在 /static/upload目录下 ,并且以源文件的名称命名
    :param fileobj: 文件对象
    :param upload:
    :return:
    """
    filename = os.path.join(settings.BASE_DIR, 'static', upload, fileobj.name)
    with open(filename, 'wb') as f:
        for chunk in fileobj.chunks():
            f.write(chunk)


import time


def saveupfilemd5(fileobj):
    """

    :param fileobj: 上传的文件
    :return:
    """
    rawfilename = fileobj.name + str(time.time())
    newfilenamemd5 = hashlib.md5(rawfilename.encode(encoding='UTF-8')).hexdigest()
    newfilename = newfilenamemd5 + "." + fileobj.name.rsplit('.', maxsplit=2)[-1]
    filename = os.path.join(settings.BASE_DIR, 'static', 'upload', newfilename)
    with open(filename, 'wb') as f:
        for chunk in fileobj.chunks():
            f.write(chunk)
    return newfilename
